<?php

namespace App\Module\User\Service;

use App\Amqp\Producer\FootPublishProducer;
use App\Component\Wechat\WechatFactory;
use App\Constants\Constant;
use App\Exception\AppException;
use App\Model\Agree;
use App\Model\Foot;
use App\Model\Resource;
use App\Module\User\Request\Foot\CreateRequest;
use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class FootService {

    /**
     * @Inject()
     * @var AuthManager $authManager
     */
    private $authManager;

    /**
     * @Inject()
     * @var ChildService $childService
     */
    private $childService;

    /**
     * @Inject()
     * @var Producer $producer
     */
    private $producer;

    /**
     * @Inject()
     * @var WechatFactory $wechatFactory
     */
    private $wechatFactory;

    public function search($child_id,$is_public,$pagesize){
        $query = Foot::query()->with("resources")->withCount("agrees as agrees")->latest("foot_id");

        if(!empty($child_id)){
            $query->where("child_id",$child_id);
        }
        if(!empty($is_public)){
            $query->where("is_public",$is_public);
        }

        $data = $query->paginate($pagesize);
        $data->getCollection()->transform(function($model){
            if($this->authManager->guard(Constant::USER)->guest()){
                $already_agree = false;
            }else{
                $already_agree = $model->agrees()->where("user_id",$this->authManager->guard(Constant::USER)->user()->getId())->exists();
            }
            $model->setAttribute("already_agree",$already_agree);
            return $model->append(['date_of_add_time','time_of_add_time']);
        });
        return $data;
    }

    public function create(CreateRequest $request){

        //内容检测
        if(!empty($request->input("content")) && $this->wechatFactory->getMiniProgram()->content_security->checkText($request->input("content"))['errcode'] != 0){
            throw new AppException("违规内容,无法发布");
        }

        return Db::transaction(function () use($request){
            $child = $this->childService->getById($request->input("child_id"));
            $foot = new Foot();
            $foot->fill($request->all());
            $foot->setAttribute("child_name",$child->getAttribute("name"));
            $foot->setAttribute("child_photo",$child->getAttribute("photo"));
            $foot->setAttribute("source",Constant::SOURCE_USER);
            $foot->setAttribute("source_id",$this->authManager->guard(Constant::USER)->user()->getId());
            $foot->setAttribute("source_name",$this->authManager->guard(Constant::USER)->user()->username);
            $foot->save();

            $this->producer->produce(new FootPublishProducer(['user_id'=>$this->authManager->guard(Constant::USER)->user()->getId(),'source_id'=>$foot->getAttribute("foot_id")]));

            if(!$request->has(["resources"])){
                return;
            }

            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$foot->foot_id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_FOOT);
                $resource->save();
            }
        });
    }

    public function delete($id){
        return Db::transaction(function () use ($id){
            $model = Foot::query()->where([['foot_id',$id],['source',Constant::SOURCE_USER],['source_id',$this->authManager->guard(Constant::USER)->user()->getId()]])->first();
            if(!$model){
                throw new AppException("非原发布者,无法删除!");
            }
            $model->delete();
            if($model->resource_type != 0){
                Resource::query()->where([['source_id',$id],['origin',Constant::ORIGIN_FOOT]])->delete();
            }
        });
    }

    public function agree($id){
        $query = Agree::query()->where([['source_id',$id],['user_id',$this->authManager->guard(Constant::USER)->user()->getId()],['origin',Constant::ORIGIN_FOOT]]);
        if($query->exists()){
            return $query->delete();
        }
        $model = new Agree();
        $model->setAttribute("source_id",$id);
        $model->setAttribute("user_id",$this->authManager->guard(Constant::USER)->user()->getId());
        $model->setAttribute("origin",Constant::ORIGIN_FOOT);
        return $model->save();
    }

    public function publish($id){
        $model = Foot::query()->findOrFail($id);
        $model->setAttribute("is_public",$model->getAttribute("is_public") % 2 + 1);
        return $model->save();
    }
}